package main

import (
	"fmt"
	"sync"
)

func incrementer(nums []int) <-chan int {
	l := len(nums)
	var out chan int
	if l < 10 {
		out = make(chan int, 1)
		go func() {
			sum := sum(nums)
			out <- sum
			close(out)
		}()
		return out
	}

	mod := l % 10
	reduceTimes := l / 10
	if mod > 0 {
		reduceTimes++
	}
	out = make(chan int, reduceTimes)
	var wg sync.WaitGroup
	wg.Add(reduceTimes)
	for i := 0; i < reduceTimes; i++ {
		var reduceNums []int
		if i+1 == reduceTimes {
			reduceNums = nums[i*10:]
		} else {
			reduceNums = nums[i*10 : (i+1)*10]
		}
		go func(rms []int) {
			out <- sum(rms)
			wg.Done()
		}(reduceNums) //当参数传进去会自动复制slice
		//错误示例 不会创建新的切片，引用方法的内的切片 指向的是同一个切片地址
		//go func() {
		//	out <- sum(reduceNums)
		//	wg.Done()
		//}()

	}
	wg.Wait()
	close(out)
	return out
}

func sum(nums []int) int {
	var sum int
	for _, v := range nums {
		sum += v
	}
	return sum
}

func main() {
	nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21}
	sumResult := incrementer(nums)
	finalResult := 0
	for v := range sumResult {
		finalResult += v
	}
	fmt.Println("finalResult=", finalResult)
}
